import {
  ui
} from '~/tools/ui'
import {
  ds
} from '~/tools/data'
import {
  dsx
} from '~/tools/datax'
import {
  rsa
} from '~/tools/rsa';

export const exTool = {
  async exchange(curUser, paramObj) {
    const {
      ex
    } = paramObj
    const obj = JSON.parse(rsa.decrypt(ex))
    if (!obj) return ui.toast(false, '错误的兑换码')
    // console.log(obj)
    this.curUser = curUser
    this.param = obj
    if (!this.checkAuthority()) return ui.toast(false, '无权限或不在有效期内')
    const tickets = await this.findTickets()
    if (!tickets) return ui.toast(false, '无可兑换水票')
    const ticketIds = tickets.map(ele => ele._id)
    wx.navigateTo({
      url: '/pages/usercenter/exTicket/exTicket?action=exchange&ticketIds=' + JSON.stringify(ticketIds),
    })
  },
  checkAuthority() {
    const curUser = this.curUser
    const {
      allowType,
      owner,
      userList,
      start,
      end
    } = this.param
    // console.log(this.param)
    if (allowType == '店员') {
      return ['master', 'admin', 'staff', 'delivery'].indexOf(curUser.role) >= 0
    } else if (allowType == '指定用户') {
      return userList.find(ele => ele.id && ele.id == curUser._id)
    } else if (allowType == '仅自己') {
      return owner.id && owner.id == curUser._id
    }
    const d = new Date().getTime()
    return d >= start && d <= end
  },
  async findTickets() {
    const {
      exOrder,
      owner
    } = this.param
    const _ = ds.cmd
    const userRes = await ds.coll('users')
      .where({
        _id: _.eq(owner.id)
      })
      .orderBy('createTime', 'desc')
      .get()
    const ownerUser = userRes.data[0]
    // console.log(ownerUser)
    if (!ownerUser) return false
    const orderRes = ds.coll('orders')
      .where({
        _openid: _.eq(ownerUser._openid),
        ticketInfo: _.exists(true),
        payStatus: 'success'
      })
      .get()
    let tickets = (await orderRes).data
    tickets = tickets.filter(ele => {
      const info = ele.ticketInfo
      return (info.totalAmount || 0) - (info.used || 0) > 0
    })

    return this.chooseTickets(exOrder, tickets)
  },
  chooseTickets(exOrder, ticketList) {
    // console.log(exOrder, ticketList)
    if (!ticketList || !(ticketList.length > 0)) return false
    if (exOrder.startsWith('余票')) { // 余票多的，余票少的
      ticketList.sort((a, b) => {
        const nA = (a.ticketInfo.totalAmount || 0) - (a.ticketInfo.used || 0)
        const nB = (b.ticketInfo.totalAmount || 0) - (b.ticketInfo.used || 0)
        // console.log(nA, nB, (exOrder == '余票多的' ? -1 : 1) * (nA - nB))
        return (exOrder == '余票多的' ? -1 : 1) * (nA - nB)
      })
      return ticketList[0]
    }
    if (exOrder.endsWith('水票')) { // 最新水票, 最旧水票
      ticketList.sort((a, b) => {
        return (exOrder == '最新水票' ? -1 : 1) * (a.createTime - b.creatTime)
      })
      return ticketList[0]
    }

    if (exOrder == '兑换人自选') {
      return ticketList
    }

    // console.log(ticketList[0])
    return false
  },
  useTicket(ticket) { // ticket: ticket order
    const end = (success, msg, resolve, res) => {
      ui.loading(false)
      if (msg) ui.toast(success, msg)
      resolve(res)
    }
    return new Promise((resolve, reject) => {
      const ticketInfo = ticket.ticketInfo
      const left = (ticketInfo.totalAmount || 0) - (ticketInfo.used || 0)
      if (left < 1) return end(false, '剩余水票数不足', resolve, 'no ticket left')
      const msg = (left == 1 ? '1' : ('1-' + left))
      ui.text('输入兑换数量', `可兑换${msg}桶`, (res, content) => {
        if (!res) return end(false, null, reject, 'cancel')

        const useNum = parseInt(content)
        if (!useNum || useNum < 1 || useNum > left) return end(false, '输入错误', reject, 'input error')

        // console.log(ticket, useNum)
        ui.loading(true)
        wx.cloud.callFunction({
            name: 'useTicket',
            data: {
              _id: ticket._id || ticket.id,
              useNum
            }
          })
          .then(res => {
            end(true, '', resolve, res)
          })
          .catch(err => {
            end(false, '', reject, 'error')
          })
      })
    })
  },
  cancelTicketOrder(order) {
    return new Promise((resolve, reject) => {
      dsx.cloudUpdate('orders', order._id, {
        status: '已取消'
      }).then(async res => {
        if (!res.result?.errMsg?.endsWith(':ok')) reject(res)

        wx.cloud.callFunction({
            name: 'useTicket',
            data: {
              _id: order.ticketOrderId,
              useNum: -Number(order.goodsList[0].num)
            }
          })
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    })
  },
  setUsage(order, used) {
    return dsx.cloudUpdate('orders', order._id, {
      ticketInfo: {
        used
      }
    })
  }
}